from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
import math


class CustomPagination(PageNumberPagination):
    page_size_query_param = 'pageSize'
    page_query_param = 'current'
    

    def get_paginated_response(self, data) -> Response:
        paginate = self.request.query_params.get('paginate','true')
        if paginate == 'true':
            total = self.page.paginator.count
            page_size = self.page.paginator.per_page
            
            page_number = int(self.request.query_params.get(self.page_query_param, 1))

            return Response({
                'code': 200,
                'page': {
                    'current': page_number,
                    'total': total,
                    'pageSize': page_size,
                    'total_page': math.ceil(total / page_size)
                },
                'data': data
            })
        else:
            return Response({
                'code': 200,
                'data': data
            })

    def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """
        paginate = request.query_params.get('paginate','true')
        print(paginate)
        if paginate == 'true':
            return super(CustomPagination,self).paginate_queryset(queryset, request, view)
        paginator = self.django_paginator_class(queryset, queryset.count())
        page_number = 1
        if queryset.count() != 0:
            self.page = paginator.page(page_number)
        else:
            self.page = list()
        self.request = request
        return list(self.page)


